package xyz.syyrjx.code;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 封装jackson的json转换器
 *
 * @author 大地崩坏苍蝇兽
 * @date 2023/1/5 - 17:39
 */
public class SyyrjxRpcCoder {

    private final static Logger LOGGER = LoggerFactory.getLogger(SyyrjxRpcCoder.class);
    private final static byte[] DEFAULT_BYTES = new byte[0];


    public static <T> T StringToObject(String str) {
        String[] strings = str.substring(1, str.length() - 1).split(", ");
        byte[] objectBytes = new byte[strings.length];
        for (int i = 0; i < objectBytes.length; i++) {
            objectBytes[i] = Byte.parseByte(strings[i]);
        }
        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null;

        try{
            bais = new ByteArrayInputStream(objectBytes);
            ois = new ObjectInputStream(bais);
            return (T) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            LOGGER.error("数据反序列化出错：" + e.getMessage());
            e.printStackTrace();
            return null;
        } finally {
            if (bais != null) {
                try {
                    bais.close();
                } catch (IOException e) {
                    LOGGER.error("数据反序列化出错：" + e.getMessage());
                    e.printStackTrace();
                }
            }
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    LOGGER.error("数据反序列化出错：" + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }

    public static byte[] ObjectToString(Object obj){
        ByteArrayOutputStream baos = null;
        ObjectOutputStream oos = null;
        try{
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            oos.flush();
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (IOException e) {
            LOGGER.error("数据序列化出错：" + e.getMessage());
            e.printStackTrace();
            return DEFAULT_BYTES;
        } finally {
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    LOGGER.error("数据反序列化出错：" + e.getMessage());
                    e.printStackTrace();
                }
            }
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    LOGGER.error("数据反序列化出错：" + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }
}
